package com.gege.hmily.order.service.impl;

import com.gege.hmily.order.client.account.AccountClient;
import com.gege.hmily.order.enums.OrderStatusEnum;
import com.gege.hmily.order.mapper.OrderMapper;
import com.gege.hmily.order.model.Order;
import com.gege.hmily.order.service.OrderService;
import com.gege.hmily.request.PayRequest;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author gechenpeng
 * @date 2021-05-29
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;

    private final AccountClient accountClient;

    @Autowired(required = false)
    public OrderServiceImpl(OrderMapper orderMapper, AccountClient accountClient) {
        this.orderMapper = orderMapper;
        this.accountClient = accountClient;
    }

    @Override
    public Order saveOrder(Order order) {
        order.setCreateTime(new Date());
        order.setNumber("1");
        order.setStatus(OrderStatusEnum.NOT_PAY.getCode());
        order.setProductId("1");
        order.setCount(1);
        order.setUserId("10000");
        orderMapper.insert(order);
        return order;
    }

    @Override
    @HmilyTCC(confirmMethod = "payConfirm", cancelMethod = "payCancel")
    public void pay(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        orderMapper.updateById(Order.builder()
                .id(orderId)
                .status(OrderStatusEnum.PAYING.getCode())
                .build());

        accountClient.pay(PayRequest.builder()
                .userId(order.getUserId())
                .amount(order.getTotalAmount())
                .build());
    }

    public void payConfirm(Long orderId) {
        orderMapper.updateById(Order.builder()
                .id(orderId)
                .status(OrderStatusEnum.PAY_SUCCESS.getCode())
                .build());
    }

    public void payCancel(Long orderId) {
        orderMapper.updateById(Order.builder()
                .id(orderId)
                .status(OrderStatusEnum.PAY_FAIL.getCode())
                .build());
    }
}
